package com.jiayou.activity

import android.Manifest
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory

import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.FileUtils
import android.provider.OpenableColumns
import android.text.InputType
import android.view.View
import android.webkit.MimeTypeMap
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONUtil
import com.jiayou.R
import com.jiayou.tool.AndroidTool
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import kotlinx.android.synthetic.main.activity_user_info.*
import kotlinx.android.synthetic.main.menu_item.*
import kotlinx.android.synthetic.main.menu_item.nicheng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.lang.Exception
import java.util.*
import kotlin.concurrent.thread
import kotlin.random.Random

class UserInfoActivity : AppCompatActivity(), View.OnClickListener {

    private val properties = Properties()
    private lateinit var uri: String

    private var resoult: String = ""

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)
        AndroidTool.fullScreen(this, "#F2F2F2")

        properties.load(application.assets.open("im.properties"))
        uri = properties["im.uri"].toString() + ":" + properties["im.port"].toString()

        fanhui.setOnClickListener(this)
        nichenglayout.setOnClickListener(this)
        gexingqianminglayout.setOnClickListener(this)
        xingbielayout.setOnClickListener(this)
        huantouxiang.setOnClickListener(this)
        initText()
        initTouxiang()
    }

    private fun initText() {
        nicheng.text = MainActivity.petname
        imhao.text = MainActivity.ID
        xingbie.text = if (MainActivity.gender == 0) "女" else "男"
        gexingqianming.text = MainActivity.description
    }

    private fun initTouxiang() {
        thread {
            val bodyStream = HttpRequest.get("http://$uri/im/userinfo/getImgByName").form("img", MainActivity.img)
                .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                .execute()
                .bodyStream()

            runBlocking {
                withContext(Dispatchers.Main) {
                    wodetouxiang.setImageBitmap(BitmapFactory.decodeStream(bodyStream))
                }
            }
        }
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.fanhui -> {
                onBackPressed()
            }
            R.id.gexingqianminglayout -> {
                try {
                    updateDescription()
                } catch (e: Exception) {
                    Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
                }
            }
            R.id.nichenglayout -> {
                try {
                    updataPetname()
                } catch (e: Exception) {
                    Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
                }
            }
            R.id.xingbielayout -> {
                try {
                    updataGender()
                } catch (e: Exception) {
                    Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
                }
            }
            R.id.huantouxiang -> {
                //动态申请获取访问 读写磁盘的权限
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        101
                    );
                } else {
                    //打开相册
                    val intent = Intent(Intent.ACTION_GET_CONTENT);
                    //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
                    intent.type = "image/*";
                    startActivityForResult(intent, 102); // 打开相册

                }
            }
        }
    }


    //更新昵称
    private fun updataPetname() {
        Toast.makeText(this, "昵称的长度不超过10喔", Toast.LENGTH_SHORT).show()
        val builder = QMUIDialog.EditTextDialogBuilder(this)
        builder.setTitle("昵称修改")
            .setPlaceholder("清输入您的昵称")
            .setInputType(InputType.TYPE_CLASS_TEXT)
            .addAction(
                "取消"
            ) { dialog, index -> dialog.dismiss() }
            .addAction(
                "确定"
            ) { dialog, index ->
                val text: CharSequence? = builder.editText.text
                if (text != null && text.isNotEmpty()) {
                    if (text.isBlank())
                        Toast.makeText(this, "昵称为空", Toast.LENGTH_SHORT).show()
                    if (text.length > 10)
                        Toast.makeText(this, "昵称太长啦", Toast.LENGTH_SHORT).show()
                    else {
                        thread {
                            runBlocking {
                                val parse = JSONUtil.parseObj(
                                    HttpRequest.post("http://${uri}/im/userinfo/updatePetname")
                                        .form(
                                            mapOf(
                                                "username" to MainActivity.ID,
                                                "petname" to text.toString()
                                            )
                                        )
                                        .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                                        .execute()
                                        .body()
                                )
                                if (parse["code"].toString().toInt() == 200) {
                                    MainActivity.petname = text.toString()
                                    nicheng.text = text.toString()
                                    resoult = MainActivity.petname
                                    withContext(Dispatchers.Main) {
                                        Toast.makeText(
                                            this@UserInfoActivity,
                                            "更新成功",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Toast.makeText(this, "请输入ID", Toast.LENGTH_SHORT).show()
                }
                dialog.dismiss()
            }
            .show()
    }

    //更新性别
    private fun updataGender() {
        thread {
            runBlocking {
                val parse = JSONUtil.parseObj(
                    HttpRequest.post("http://${uri}/im/userinfo/updateGender")
                        .form(
                            mapOf(
                                "username" to MainActivity.ID,
                                "gender" to if (MainActivity.gender == 0) 1 else 0
                            )
                        )
                        .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                        .execute()
                        .body()
                )
                if (parse["code"].toString().toInt() == 200) {
                    MainActivity.gender = if (MainActivity.gender == 0) 1 else 0
                    xingbie.text = if (MainActivity.gender == 0) "女" else "男"
                    withContext(Dispatchers.Main) {
                        Toast.makeText(
                            this@UserInfoActivity,
                            "更新成功",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        }
    }

    //更新个性签名
    private fun updateDescription() {
        Toast.makeText(this, "个性签名的长度不超过15喔", Toast.LENGTH_SHORT).show()
        val builder = QMUIDialog.EditTextDialogBuilder(this)
        builder.setTitle("个性签名")
            .setPlaceholder("请输入个性签名")
            .setInputType(InputType.TYPE_CLASS_TEXT)
            .addAction(
                "取消"
            ) { dialog, index -> dialog.dismiss() }
            .addAction(
                "确定"
            ) { dialog, index ->
                val text: CharSequence? = builder.editText.text
                if (text != null && text.isNotEmpty()) {
                    if (text.isBlank())
                        Toast.makeText(this, "昵称为空", Toast.LENGTH_SHORT).show()
                    if (text.length > 15)
                        Toast.makeText(this, "昵称太长啦", Toast.LENGTH_SHORT).show()
                    else {
                        thread {
                            runBlocking {
                                val parse = JSONUtil.parseObj(
                                    HttpRequest.post("http://${uri}/im/userinfo/updateDescription")
                                        .form(
                                            mapOf(
                                                "username" to MainActivity.ID,
                                                "description" to text.toString()
                                            )
                                        )
                                        .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                                        .execute()
                                        .body()
                                )
                                if (parse["code"].toString().toInt() == 200) {
                                    MainActivity.description = text.toString()
                                    gexingqianming.text = text.toString()
                                    withContext(Dispatchers.Main) {
                                        Toast.makeText(
                                            this@UserInfoActivity,
                                            "更新成功",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }
                            }
                        }
                    }
                } else {
                    Toast.makeText(this, "请输入ID", Toast.LENGTH_SHORT).show()
                }

                dialog.dismiss()
            }
            .show()
    }


    override fun onBackPressed() = finish()


    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            102 -> if (resultCode === Activity.RESULT_OK) {
                thread {
                    try {
                        val obj = JSONUtil.parseObj(
                            HttpRequest.post("http://${uri}/im/userinfo/updateImg")
                                .form(
                                    "img",
                                    uriToFileQ(this@UserInfoActivity, uri = data?.data!!)
                                )
                                .form("id", MainActivity.ID)
                                .header("auth", "73913da7-508b-4646-b8ae-ef6458f41153")
                                .execute().body()
                        )
                        if (obj["code"].toString().toInt() == 200) {
                            MainActivity.img = obj["data"].toString()
                            initTouxiang()
                            runOnUiThread {
                                Toast.makeText(this, "更新成功！", Toast.LENGTH_SHORT).show()
                            }
                        } else {
                            runOnUiThread {
                                Toast.makeText(this, obj["data"].toString(), Toast.LENGTH_SHORT).show()
                            }
                        }
                    } catch (e: Exception) {

                    }

                }
            }

            else -> {
            }
        }
    }


    companion object {
        @RequiresApi(Build.VERSION_CODES.Q)
        private fun uriToFileQ(context: Context, uri: Uri): File? =
            if (uri.scheme == ContentResolver.SCHEME_FILE)
                File(requireNotNull(uri.path))
            else if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
                //把文件保存到沙盒
                val contentResolver = context.contentResolver
                val displayName = run {
                    val cursor = contentResolver.query(uri, null, null, null, null)
                    cursor?.let {
                        if (it.moveToFirst())
                            it.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                        else null
                    }
                } ?: "${System.currentTimeMillis()}${Random.nextInt(
                    0,
                    9999
                )}.${MimeTypeMap.getSingleton()
                    .getExtensionFromMimeType(contentResolver.getType(uri))}"

                val ios = contentResolver.openInputStream(uri)
                if (ios != null) {
                    File("${context.externalCacheDir!!.absolutePath}/$displayName")
                        .apply {
                            val fos = FileOutputStream(this)
                            FileUtils.copy(ios, fos)
                            fos.close()
                            ios.close()
                        }
                } else null
            } else null
    }
}